package gcb.metalsys.controller.cop;


import gcb.metalsys.entity.cop.CopProduct;
import gcb.metalsys.enums.ProductEnum;
import gcb.metalsys.service.cop.impl.CopWarehouseServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import gcb.metalsys.base.ResultUtil;
import gcb.metalsys.base.dto.ResultDTO;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import gcb.metalsys.dto.cop.InsertOrderDTO;
import gcb.metalsys.dto.cop.OrderDTO;
import gcb.metalsys.dto.cop.OrderStatementDTO;
import gcb.metalsys.entity.auth.AuthUser;
import gcb.metalsys.entity.cop.CopOrderDetail;
import gcb.metalsys.enums.OrderEnum;
import gcb.metalsys.service.auth.AuthUserService;
import gcb.metalsys.service.cop.CopOrderDetailService;
import gcb.metalsys.service.cop.CopOrderService;
import gcb.metalsys.entity.cop.CopOrder;

/**
 * @since 2019-12-31
 */
@Api(value = "订单接口", tags = "贵金属领入与交出")
@RestController
@RequestMapping("/copOrder")
public class CopOrderController {

    @Autowired
    private CopOrderService copOrderService;
    @Autowired
    private CopOrderDetailService copOrderDetailService;
    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private CopWarehouseServiceImpl copWarehouseService;

    @PostMapping
    @ApiOperation(value = "插入")
    public ResultDTO insertOne(Authentication authentication,
                               @RequestBody InsertOrderDTO insertOrderDTO) throws Exception {
        CopOrder copOrder = new CopOrder();
        BeanUtils.copyProperties(insertOrderDTO,copOrder);
        AuthUser userDetails = authUserService.getUserDetails(authentication);
//        copOrder.setOrderStatus(OrderEnum.START.getCode());
        copOrder.setOrderUserId(userDetails.getUserId());
        copOrderService.save(copOrder);

        if(copOrder.getOrderStatus()==1){
            copWarehouseService.plusWarehouse(insertOrderDTO.getProductId(),userDetails.getUserId(),insertOrderDTO.getProductSize());
        }else {
            copWarehouseService.subtractWarehouse(insertOrderDTO.getProductId(),userDetails.getUserId(),insertOrderDTO.getProductSize());
        }

        CopOrderDetail copOrderDetail = new CopOrderDetail();
        BeanUtils.copyProperties(insertOrderDTO,copOrderDetail);
        copOrderDetail.setOrderId(copOrder.getOrderId());
        copOrderDetailService.save(copOrderDetail);

        return ResultUtil.Success(copOrder.getOrderId());
    }


    @PutMapping
    @ApiOperation(value = "按ID修改")
    public ResultDTO updateById(@RequestBody CopOrder copOrder) throws Exception {
        copOrderService.updateById(copOrder);
        return ResultUtil.Success();
    }

    @DeleteMapping("/{id:\\d+}")
    @ApiOperation("按ID删除")
    public ResultDTO deleteById(@PathVariable Long id) throws Exception {
        copOrderService.removeById((long) id);
        return ResultUtil.Success();
    }

    @GetMapping()
    @ApiOperation("查询、分页返回")
    public ResultDTO selectEntityPage(Authentication authentication,
                                            @RequestParam(value = "page", defaultValue = "1") int pageNum,
                                            @RequestParam(value = "limit", defaultValue = "8") int pageSize,
                                      String clientName)throws Exception{
        AuthUser userDetails = authUserService.getUserDetails(authentication);
        Long userId = userDetails.getUserId();


        List<Map<String, Object>> data = copOrderService.selectOrderList(userId, clientName, (pageNum-1)*pageSize, pageSize);


        for (Map<String, Object> tempMap : data) {
            for (OrderEnum value : OrderEnum.values()) {
                if (value.getCode().equals(tempMap.get("order_status"))) {
                    tempMap.put("order_status",value.getMessage());
                }
            }
        }



        int count = copOrderService.countOrderList(userId, clientName);
        return ResultUtil.Success(data,count);

    }

    @GetMapping("/{id:\\d+}")
    @ApiOperation("ID查询")
    public ResultDTO selectEntityPage(@PathVariable Long id)throws Exception{
        return ResultUtil.Success(copOrderService.getById(id));
    }

    @PostMapping("/statement")
    @ApiOperation("报表查询")
    public ResultDTO selectStatement(Authentication authentication,
                                      @RequestBody OrderStatementDTO orderStatementDTO)throws Exception{
        List<Long> userId = authUserService.getUserAndChildId(authentication).stream().map(AuthUser::getUserId).collect(Collectors.toList());
        orderStatementDTO.setUserId(userId);
        List<OrderDTO> orderDTOS;
        if (orderStatementDTO.getOrderStatus().size() >1) {
            orderDTOS = copOrderService.selectRunningStatement(orderStatementDTO);
        }else {
            orderDTOS = copOrderService.selectStatement(orderStatementDTO);
        }
        for (OrderDTO orderDTO : orderDTOS) {
            orderDTO.statusConverse();
        }
        return ResultUtil.Success(orderDTOS);
    }

}
